package pers.w.chaptertalk;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.GradientDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;

import pers.w.chaptertalk.funs.BookInfo;
import pers.w.chaptertalk.funs.ChapterThread;
import pers.w.chaptertalk.funs.Fun;
import pers.w.chaptertalk.funs.db.Tab_Book;
import pers.w.chaptertalk.funs.db.Tab_Chapter;
import pers.w.chaptertalk.reader.ReaderActivity;
import pers.w.chaptertalk.ui.ListViewAdapter;

public class ShowAndAddBookActivity extends AppCompatActivity implements View.OnClickListener {
    BookInfo bookinfo;//在初始化的时候把对应的info指针赋值过去，就可以直接修改
    ImageView iv_book;
    TextView tv_bookName, tv_manyInfo, tv_last_chapter, tv_introduction;
    LinearLayout ll_main_info;
    ListView lv_chapter_menu;
    Button btn_refresh_chapter;
    Button btn_add_book;
    ListViewAdapter.ListItemView listItemView;
    //private HashMap<Integer, Bitmap> bitmaps = new HashMap<>();//只存储一个值，k为1
    //private List<BookInfo> bookInfos = new ArrayList<>();
    private Tab_Book tbBook;

    Handler handler = new Handler(new Handler.Callback(){
        @Override
        public boolean handleMessage(@NonNull Message msg) {

            if (Fun.isDebug()) Log.d("handler", "msg what is " + msg.what);
            switch (msg.what) {
                case ChapterThread.HANDLER_CHAPTER_THREAD_MSG:
                    lv_adapter.notifyDataSetChanged();
                    btn_refresh_chapter.setEnabled(false);
                    tv_last_chapter.setText(String.format(getString(R.string.chapterInfoFormatString), msg.arg1, bookinfo.getFieldValue(R.string.info_lastChapterName)));
                    tv_introduction.setText(bookinfo.getFieldValue(R.string.info_introduction));
                    break;
                case 2:

                    iv_book.setImageBitmap(bookinfo.getImage_bmp());

                    listItemView.image1.setImageBitmap(bookinfo.getImage_bmp());
                    draw_ll_main_info(bookinfo.getImage_bmp());

                    break;
            }
            return false;
        }
    }) ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_show_and_add_book);
        ActionBar actionBar = getSupportActionBar();
        // 显示返回按钮
        assert actionBar != null;
        actionBar.setDisplayHomeAsUpEnabled(true);
        // 去掉logo图标
        actionBar.setDisplayShowHomeEnabled(false);
//创建数据表
        tbBook = new Tab_Book(this);
        //把传递的参数返回成bookinfo，方便使用Serializable
        listItemView = (ListViewAdapter.ListItemView) Fun.SHARE_MAP.get(R.string.SHARE_LISTITEM);
        assert listItemView != null;
        bookinfo = listItemView.bookInfo;
        //bookInfos.add(bookinfo);
        iv_book = findViewById(R.id.iv_book_img);
        BitmapDrawable iv_drawable = (BitmapDrawable) listItemView.image1.getDrawable();
        iv_book.setImageDrawable(iv_drawable);
        Fun.SHARE_MAP.remove(R.string.SHARE_LISTITEM);


        tv_bookName = findViewById(R.id.tv_book_name);
        tv_bookName.setText(bookinfo.getFieldValue(R.string.info_name));

        tv_manyInfo = findViewById(R.id.tv_book_manyinfo);
        tv_manyInfo.setText(String.format("%s*%s*%s", bookinfo.getFieldValue(R.string.info_type), bookinfo.getFieldValue(R.string.info_author), bookinfo.getFieldValue(R.string.info_lastUpdateTime)));

        setTV_introduction();

        ll_main_info = findViewById(R.id.ll_main_info);

        if (null != iv_drawable) {
            draw_ll_main_info(iv_drawable.getBitmap());
        }
        chapter_list = new ArrayList<>();
        setTV_last_chapter();
        setLv_chapter_menu();
        setBTNs();
        setBtn_add_book();



    }

    @Override
    protected void onDestroy() {
        tbBook.close();
        super.onDestroy();
    }

    private void setTV_introduction() {
        tv_introduction = findViewById(R.id.tv_introduction);
        tv_introduction.setText(bookinfo.getFieldValue(R.string.info_introduction));
        tv_introduction.setOnClickListener(this);
    }

    //根据图片内容设置背景
    //https://blog.csdn.net/houshunwei/article/details/17392409
    private void draw_ll_main_info(Bitmap bmp) {
        int x = new Random().nextInt(bmp.getWidth() - 1);
        int[] colors = {bmp.getPixel(x, 10), bmp.getPixel(x, 25), bmp.getPixel(x, 40),};//分别为开始颜色，中间夜色，结束颜色
        //如果第三个色太黑，改位白色
        byte[] rgb = Fun.intToByteArray(colors[2]);
        if ((0.3 * rgb[0] + 0.6 * rgb[1] + 0.1 * rgb[2]) < 100)
            colors[2] = 0xFFFFFF;

        GradientDrawable gd = new GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM, colors);
        ll_main_info.setBackground(gd);
    }


    private void setBtn_add_book() {
        btn_add_book = findViewById(R.id.btn_add_book);
        if (bookinfo.getID() > 0) {//有id>0，说明已经在数据库了
            btn_add_book.setText("已添加");
            btn_add_book.setEnabled(false);
        } else {//没有id，就查询一下，如果有，也禁用
            List<BookInfo> books = tbBook.get_books(bookinfo.getFieldValue(R.string.info_uri));
            if (books.size() > 0) {
                btn_add_book.setText("已添加");
                btn_add_book.setEnabled(false);
                bookinfo = books.get(0);
            }
        }
        btn_add_book.setOnClickListener(this);
    }

    private void setTV_last_chapter() {
        tv_last_chapter = findViewById(R.id.tv_last_update);
        tv_last_chapter.setText(String.format("▶共?章，最后章节：%s", bookinfo.getFieldValue(R.string.info_lastChapterName)));
    }

    private List<Map<String, String>> chapter_list;
    SimpleAdapter lv_adapter;

    private void setLv_chapter_menu() {
        lv_chapter_menu = findViewById(R.id.lv_chapter_menu);

        lv_adapter = new SimpleAdapter(this, chapter_list, android.R.layout.simple_list_item_2,
                new String[]{Tab_Chapter.CHAPTERNAME, Tab_Chapter.CHAPTERUPDATETIME},
                new int[]{android.R.id.text1, android.R.id.text2});
        lv_chapter_menu.setAdapter(lv_adapter);
        getChapterMenu();
        /**/
        lv_chapter_menu.setOnScrollListener(new AbsListView.OnScrollListener() {
            private int oldIndex;
            private boolean isGone = false;

            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                if (scrollState == SCROLL_STATE_TOUCH_SCROLL) {//状态的意思为当手点击屏幕准备滑动时
                    oldIndex = view.getLastVisiblePosition();
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                //firstVisibleItem：当前能看见的第一个item的ID（从0开始）
                //visibleItemCount：当前可见的item总数
                //totalItemCount：列表中适配器总数量，也就是整个ListView中item总数
                int newIndex = view.getLastVisiblePosition();
                if (Fun.isDebug())
                    Log.d("scroll", "newIndex:" + newIndex + "--oldIndex:" + oldIndex);
                //item向下滚动，手指往上滑
                if (newIndex > oldIndex && firstVisibleItem > 0 && !isGone) {
                    isGone = true;
                    ll_main_info.setVisibility(View.GONE);
                    tv_introduction.setVisibility(View.GONE);
                } else if (firstVisibleItem == 0 && isGone) {
                    isGone = false;
                    ll_main_info.setVisibility(View.VISIBLE);
                    tv_introduction.setVisibility(View.VISIBLE);
                }
            }
        });

    }

    private void setBTNs() {
        btn_refresh_chapter = findViewById(R.id.btn_refresh_chapter);
        btn_refresh_chapter.setOnClickListener(this);
        Button btn_reader = findViewById(R.id.btn_read_start);
        btn_reader.setOnClickListener(this);
    }


    private ChapterThread chapterThread ;

    private void getChapterMenu() {
        if (chapter_list.size() > 0) return;
        /*new Thread(new Runnable() {
            @Override
            public void run() {
                final String uri = bookinfo.getFieldValue(R.string.info_uri);
                Document doc=null;
                while (!stopThread){
                    try {
                        doc = Jsoup.connect(uri).timeout(5000).get();
                        break;
                    } catch (IOException e) {
                        e.printStackTrace();
                        doc=null;
                        //return;
                    }
                }

                if (Fun.isDebug()) Log.d("getChapter", uri + ": 开始获取章节");
                assert uri != null;
                Elements result_list;*/
                //if (0 == uri.indexOf(getString(R.string.天籁网))) {
                /*if (0 == uri.indexOf(getString(R.string.笔趣阁1)) || 0 == uri.indexOf(getString(R.string.笔趣阁2))) {
                    result_list = doc.select("img");
                    if (null != result_list && result_list.size() > 0 && ((String) bookinfo.getFieldValue(R.string.info_img)).isEmpty()) {//没有图片地址，从这里读取一次
                        String imgUrl = result_list.get(0).attr("src");
                        if (0 == uri.indexOf(getString(R.string.笔趣阁2)))
                            imgUrl = "https://www.biqugg.com" + imgUrl;

                        bookinfo.setFieldValue(R.string.info_img, imgUrl);

                        new WebBmpThread(bookInfos) {
                            @Override
                            public void runOnUiThread(int position) {
                                Message msg_update_image = new Message();
                                msg_update_image.what = 2;
                                handler.sendMessage(msg_update_image);
                            }
                        }.start();

                    }
                    result_list = doc.select("div[id=intro]");
                    if (null != result_list && result_list.size() > 0 && ((String) bookinfo.getFieldValue(R.string.info_introduction)).isEmpty())
                        bookinfo.setFieldValue(R.string.info_introduction, result_list.get(0).text());
                }*/

               /* assert doc != null;
                result_list = doc.select("dd");

                for (int i = 0; i < result_list.size(); i++) {
                    Map<String, String> chapter_map = new HashMap<>();

                    Elements chapterElement = result_list.get(i).select("a");
                    if (chapterElement.size() == 1) {
                        chapter_map.put(Tab_Chapter.CHAPTERNAME,
                                chapterElement.get(0).text());
                        String chapterUri = chapterElement.get(0).attr("href");
                        if (null != chapterUri && chapterUri.indexOf(uri) != 0)//如果获得的章节地址是相对路径，转为绝对路径
                            chapterUri = uri + chapterUri;
                        chapter_map.put(Tab_Chapter.CHAPTERURI, chapterUri);
                        chapter_map.put(Tab_Chapter.CHAPTERUPDATETIME, "");
                        chapter_list.add(chapter_map);
                    }
                }
                // }

                //final Elements finalResult_list = result_list;
                Message msg_showchapter = new Message();

                msg_showchapter.what = 1;
                msg_showchapter.arg1 = result_list.size();
                handler.sendMessage(msg_showchapter);

            }
        }).start();*/

        chapterThread= new ChapterThread(bookinfo,chapter_list,handler);
        chapterThread.start();
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            chapterThread.cancel();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_refresh_chapter:
                break;
            case R.id.btn_add_book:
                if (tbBook.add(bookinfo,null/*chapter_list*/) > 0) {
                    Toast.makeText(this, "添加成功", Toast.LENGTH_SHORT).show();
                    btn_add_book.setText("已添加");
                    btn_add_book.setEnabled(false);
                    bookinfo.saveBmp();
                    Fun.SHARE_MAP.put(R.string.SHARE_BOOKRACK_ADD,bookinfo);
                }
                break;
            case R.id.btn_read_start:

                Intent intent = new Intent(this, ReaderActivity.class);
                Fun.SHARE_MAP.put(R.string.SHARE_READER,bookinfo);
                startActivity(intent);
                break;
            case R.id.tv_introduction:
                 tv_introduction.setMaxLines(tv_introduction.getMaxLines() == 3 ? 20 : 3);
                break;
        }
    }
}
